//
//  HomeChildViewController.m
//  StylisticCircle
//
//  Created by wujian on 2018/5/24.
//  Copyright © 2018年 zongquankeji. All rights reserved.
//

#import "HomeChildViewController.h"
#import <WebKit/WebKit.h>
#import "NJKWebViewProgressView.h"
#import "NJKWebViewProgress.h"
#import "CZQMyMainSharView.h"

@interface HomeChildViewController ()<WKNavigationDelegate,WKUIDelegate,UIWebViewDelegate,NJKWebViewProgressDelegate>{
    
    NJKWebViewProgressView *_progressView;
    NJKWebViewProgress *_progressProxy;
}

@property (nonatomic, strong) UIWebView *webView;

@property(nonatomic,weak)UICollectionView *collectionView;

@property(nonatomic,strong)NSMutableArray *dataSource;

//分享的链接
@property(nonatomic,strong)NSString *shareLink;

@end

@implementation HomeChildViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self loadData];
    
    [_progressView setProgress:0.f animated:YES];
    
    [self.navigationController.navigationBar addSubview:_progressView];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    // Remove progress view
    // because UINavigationBar is shared with other ViewControllers
    [_progressView removeFromSuperview];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = false;
    
    UIWebView *webView = [[UIWebView alloc] init];
    webView.scalesPageToFit = YES;
    [self.view addSubview:webView];
    
    self.webView = webView;
    
    [webView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(self.view);
    }];
    
    
    _progressProxy = [[NJKWebViewProgress alloc] init];
    webView.delegate = _progressProxy;
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    
    CGFloat progressBarHeight = 2.f;
    CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, navigationBarBounds.size.height - progressBarHeight, navigationBarBounds.size.width, progressBarHeight);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    

    if (self.isHtmlString) {
        
        [webView loadHTMLString:self.content baseURL:nil];
    }
    else{
     
        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.content] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0]];
    }
    
    
    if (self.isFromActive) {
        [self showRightImageWithImageName:@"nav_more"];
    }
    
}

#pragma mark - 加载网页

- (void)loadData{
    
   [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.content] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0]];
    
}

#pragma mark - NJKWebViewProgressDelegate
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_progressView setProgress:progress animated:YES];
    
    self.title = isBlankString([_webView stringByEvaluatingJavaScriptFromString:@"document.title"], self.title) ;
    
    
}



-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *js = @"function imgAutoFit() { \
    var imgs = document.getElementsByTagName('img'); \
    for (var i = 0; i < imgs.length; ++i) {\
    var img = imgs[i];   \
    img.style.maxWidth = %f;   \
    } \
    }";
    js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width - 20];
    
    [webView stringByEvaluatingJavaScriptFromString:js];
    [webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];
}

#pragma mark - 右侧事件
-(void)rightBtnClick
{
    if (self.isFromActive) {
        
        WS(weakSelf);
        
        
        
        CZQMyMainSharView *shareView = [[CZQMyMainSharView alloc]init];
        [shareView onlyShare];
        [shareView showWithAnimation];
        
        NSMutableArray *arrM = [NSMutableArray array];
        
        
        NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
        [parmas setValue:@"报名管理" forKey:@"title"];
        [parmas setValue:@"popup_icon_registration_management" forKey:@"image"];
        [arrM addObject:parmas];
        
        NSMutableDictionary *parmas1 = [NSMutableDictionary dictionary];
        [parmas1 setValue:@"社交分享" forKey:@"title"];
        [parmas1 setValue:@"popup_icon_social sharing" forKey:@"image"];
        [arrM addObject:parmas1];
        
        NSMutableDictionary *parmas2 = [NSMutableDictionary dictionary];
        [parmas2 setValue:@"下载二维码" forKey:@"title"];
        [parmas2 setValue:@"popup_icon_download_qr_code" forKey:@"image"];
        [arrM addObject:parmas2];
        
        NSMutableDictionary *parmas3 = [NSMutableDictionary dictionary];
        [parmas3 setValue:@"活动编辑" forKey:@"title"];
        [parmas3 setValue:@"popup_icon_active_editor" forKey:@"image"];
        [arrM addObject:parmas3];
        
        shareView.layout.itemSize =  CGSizeMake(SCREENWIDTH/4, SCREENWIDTH/4 + 20);
        shareView.titleLable.text = @"选择操作方式";
        
        shareView.shareSoursArrM = arrM;
        
        shareView.shareClick = ^(NSInteger index) {
            
            [weakSelf moreBtnClick:index];
            
        };
        
    }
}

#pragma mark - 更多回调
-(void)moreBtnClick:(NSInteger)index
{
    if (index == 0) {
        
        
    }else if (index == 1)
    {
        //社交分享
        
        WS(weakSelf);
        
        
        
        CZQMyMainSharView *shareView = [[CZQMyMainSharView alloc]init];
        [shareView onlyShare];
        [shareView showWithAnimation];
        
        NSMutableArray *arrM = [NSMutableArray array];
        
        NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
        [parmas setValue:@"朋友圈" forKey:@"title"];
        [parmas setValue:@"share_btn_moments" forKey:@"image"];
        [arrM addObject:parmas];
        
        NSMutableDictionary *parmas1 = [NSMutableDictionary dictionary];
        [parmas1 setValue:@"微信好友" forKey:@"title"];
        [parmas1 setValue:@"share_btn_wechat" forKey:@"image"];
        [arrM addObject:parmas1];
        
        NSMutableDictionary *parmas2 = [NSMutableDictionary dictionary];
        [parmas2 setValue:@"QQ空间" forKey:@"title"];
        [parmas2 setValue:@"share_btn_qzone" forKey:@"image"];
        [arrM addObject:parmas2];
        
        NSMutableDictionary *parmas3 = [NSMutableDictionary dictionary];
        [parmas3 setValue:@"QQ好友" forKey:@"title"];
        [parmas3 setValue:@"share_btn_qq" forKey:@"image"];
        [arrM addObject:parmas3];
        
        NSMutableDictionary *parmas4 = [NSMutableDictionary dictionary];
        [parmas4 setValue:@"复制链接" forKey:@"title"];
        [parmas4 setValue:@"share_btn_link" forKey:@"image"];
        [arrM addObject:parmas4];
        
        NSMutableDictionary *parmas5 = [NSMutableDictionary dictionary];
        [parmas5 setValue:@"浏览器打开" forKey:@"title"];
        [parmas5 setValue:@"share_btn_safari" forKey:@"image"];
        [arrM addObject:parmas5];
        
        shareView.shareSoursArrM = arrM;
        
        shareView.shareClick = ^(NSInteger index) {
            
            [weakSelf shareBtnClick:index];
            
        };
        
    }
    else if (index == 2)
    {
        //下载二维码
        [self  setErWeiMaWithUrl:self.content];
        
    }
    else if (index == 3)
    {
       
    }
}

#pragma mark - 分享回调
-(void)shareBtnClick:(NSInteger)index
{
    
    if (index == 0) {
        //微信朋友圈
        
        [self shareToPlatform:UMSocialPlatformType_WechatTimeLine];
        
    }else if (index == 1){
        
        //微信好友
        [self shareToPlatform:UMSocialPlatformType_WechatSession];
        
    }
    else if (index == 2){
        
        //5,//qq空间
        [self shareToPlatform:UMSocialPlatformType_Qzone];
        
    }
    else if (index == 3){
        
        //4,//QQ聊天页面
        [self shareToPlatform:UMSocialPlatformType_QQ];
        
    }
    else if (index == 4){
        
        //0, //复制链接
        UIPasteboard*pasteboard = [UIPasteboard generalPasteboard];
        
        pasteboard.string = self.content;
        
        [MBProgressHUD showText:@"链接已复制在粘贴板上"];
        
    }
    else if (index == 5){
        
        //0, //浏览器打开
        NSURL *URL = [NSURL URLWithString:self.content];
        
        /**
         ios 9 之前使用
         openURL:打开的网址
         **/
        
        if (@available(iOS 9.0, *)) {
            
            [[UIApplication sharedApplication]openURL:URL];
            
        } else {
            
            [[UIApplication sharedApplication]openURL:URL options:@{} completionHandler:^(BOOL success) {
                
            }];
            
        }
        
        
        
        /**
         ios 10 以后使用  openURL: options: completionHandler:
         这个函数异步执行，但在主队列中调用 completionHandler 中的回调
         openURL:打开的网址
         options:用来校验url和applicationConfigure是否配置正确，是否可用。
         唯一可用@{UIApplicationOpenURLOptionUniversalLinksOnly:@YES}。
         不需要不能置nil，需@{}为置空。
         ompletionHandler:如不需要可置nil
         **/
        
        
        
    }
    
    
}

- (void)shareToPlatform:(UMSocialPlatformType)platformType{
            
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    NSString *logo = [self.dict objectForKey:@"logo"];
    
    //创建网页内容对象
    NSString *urlStr = [logo stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];
    
    NSString *name = [self.dict objectForKey:@"name"];
    
    NSString *title = [self.dict objectForKey:@"title"];
    
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.isFromActive?[self.dict valueForKey:@"Title"]:[NSString stringWithFormat:@"%@通知附件",name] descr:self.isFromActive?[self.dict valueForKey:@"Content"]:title thumImage:self.isFromActive?[self.dict valueForKey:@"MainPic"]:[UIImage imageWithData:data]];
    
    //设置网页地址
    shareObject.webpageUrl = self.isFromActive?self.content:self.shareLink;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    /**
     设置分享
     
     @param data 分享返回信息
     @param error 失败信息
     @param UMSocialPlatformType 分享平台
     */
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            //错误码
            
            NSString *result;
            switch (error.code) {
                case UMSocialPlatformErrorType_Unknow:
                    result = @"未知错误";
                    break;
                case UMSocialPlatformErrorType_NotSupport:
                    result = @"不支持（url scheme 没配置，或者没有配置-ObjC， 或则SDK版本不支持或则客户端版本不支持";
                    break;
                case UMSocialPlatformErrorType_AuthorizeFailed:
                    result = @"授权失败";
                    break;
                case UMSocialPlatformErrorType_ShareFailed:
                    result = @"分享失败";
                    break;
                case UMSocialPlatformErrorType_RequestForUserProfileFailed:
                    result = @"请求用户信息失败";
                    break;
                case UMSocialPlatformErrorType_ShareDataNil:
                    result = @"分享内容为空";
                    break;
                case UMSocialPlatformErrorType_ShareDataTypeIllegal:
                    result = @"分享内容不支持";
                    break;
                case UMSocialPlatformErrorType_CheckUrlSchemaFail:
                    result = @"schemaurl fail";
                    break;
                case UMSocialPlatformErrorType_NotInstall:
                    result = @"应用未安装";
                    break;
                case UMSocialPlatformErrorType_Cancel:
                    result = @"您已取消分享";
                    break;
                case UMSocialPlatformErrorType_NotNetWork:
                    result = @"网络异常";
                    break;
                case UMSocialPlatformErrorType_SourceError:
                    result = @"第三方错误";
                    break;
                case UMSocialPlatformErrorType_ProtocolNotOverride:
                    result = @"对应的    UMSocialPlatformProvider的方法没有实现";
                    break;
                default:
                    break;
            }
            
            [MBProgressHUD showText:result];
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
    
}


/**
 生成二维码
 
 @param url 二维码的URL
 */
- (void)setErWeiMaWithUrl:(NSString *)url{
    
    url = self.content;
    
    // 1、创建滤镜对象
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 恢复滤镜的默认属性
    [filter setDefaults];
    // 2、设置数据
    NSString *string_data = url;
    // 将字符串转换成 NSdata (虽然二维码本质上是字符串, 但是这里需要转换, 不转换就崩溃)
    NSData *qrImageData = [string_data dataUsingEncoding:NSUTF8StringEncoding];
    
    // 设置过滤器的输入值, KVC赋值
    [filter setValue:qrImageData forKey:@"inputMessage"];
    
    // 3、获得滤镜输出的图像
    CIImage *outputImage = [filter outputImage];
    // 图片小于(27,27),我们需要放大
    outputImage = [outputImage imageByApplyingTransform:CGAffineTransformMakeScale(20, 20)];
    // 4、将CIImage类型转成UIImage类型
    UIImage *start_image = [UIImage imageWithCIImage:outputImage];
    
    // - - - - - - - - - - - - - - - - 添加中间小图标 - - - - - - - - - - - - - - - -
    // 5、开启绘图, 获取图形上下文 (上下文的大小, 就是二维码的大小)
    UIGraphicsBeginImageContext(start_image.size);
    // 把二维码图片画上去 (这里是以图形上下文, 左上角为(0,0)点
    [start_image drawInRect:CGRectMake(0, 0, start_image.size.width, start_image.size.height)];
    // 再把小图片画上去
    
    UIImage *icon_image = [UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString:[self.dict valueForKey:@"self.model.MainPic"] ]]];

    CGFloat icon_imageW = 200;
    CGFloat icon_imageH = icon_imageW;
    CGFloat icon_imageX = (start_image.size.width - icon_imageW) * 0.5;
    CGFloat icon_imageY = (start_image.size.height - icon_imageH) * 0.5;
    [icon_image drawInRect:CGRectMake(icon_imageX, icon_imageY, icon_imageW, icon_imageH)];
    // 6、获取当前画得的这张图片
    UIImage *final_image = UIGraphicsGetImageFromCurrentImageContext();
    // 7、关闭图形上下文
    UIGraphicsEndImageContext();
    // 8、借助UIImageView显示二维码
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        //写入图片到相册
        PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:final_image];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {

        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (success) {
                [MBProgressHUD showText:@"二维码已保存至本地相册"];
            }else
            {
                [MBProgressHUD showText:@"二维码下载失败"];
            }
            
        });
        

    }];
    
    
}



@end
